<template>
  <div class="discuss-add-container">
    <div class="back-link">
      <el-button @click="goBack" icon="el-icon-arrow-left" text>返回列表</el-button>
    </div>
    
    <h2>发布讨论</h2>
    
    <el-form :model="discussForm" :rules="rules" ref="discussFormRef" label-position="top">
      <el-form-item label="标题" prop="title">
        <el-input 
          v-model="discussForm.title" 
          placeholder="请输入讨论标题（最多100个字符）" 
          maxlength="100" 
          show-word-limit
        ></el-input>
      </el-form-item>
      
      <el-form-item label="标签">
        <div class="tags-container">
          <el-tag
            v-for="tag in discussForm.tags"
            :key="tag"
            closable
            @close="discussForm.tags = discussForm.tags.filter(t => t !== tag)"
          >
            {{ tag }}
          </el-tag>
        </div>
        <div class="predefined-tags">
          <el-tag
            v-for="tag in predefinedTags.filter(t => !discussForm.tags.includes(t))"
            :key="tag"
            effect="plain"
            @click="discussForm.tags.length < 5 && discussForm.tags.push(tag)"
            :class="{ 'tag-disabled': discussForm.tags.length >= 5 }"
          >
            {{ tag }}
          </el-tag>
        </div>
        <div class="tags-tip">最多选择5个标签</div>
      </el-form-item>
      
      <el-form-item label="内容" prop="content">
        <div class="content-editor">
          <div class="editor-toolbar">
            <el-button 
              type="text" 
              @click="togglePreview"
              :icon="previewVisible ? 'el-icon-edit' : 'el-icon-view'"
            >
              {{ previewVisible ? '编辑' : '预览' }}
            </el-button>
          </div>
          
          <div v-show="!previewVisible" class="editor-container">
            <el-input 
              v-model="discussForm.content" 
              type="textarea" 
              :rows="15" 
              placeholder="请输入讨论内容（最多5000个字符），支持Markdown格式" 
              maxlength="5000" 
              show-word-limit
            ></el-input>
          </div>
          
          <div v-show="previewVisible" class="preview-container markdown-body" v-html="renderMarkdown(discussForm.content)">
          </div>
        </div>
      </el-form-item>
      
      <el-form-item>
        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit" :loading="loading">发布</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-form-item>
    </el-form>
    
    <div class="markdown-tips">
      <h3>Markdown 语法提示：</h3>
      <ul>
        <li><code># 标题</code> - 一级标题</li>
        <li><code>## 标题</code> - 二级标题</li>
        <li><code>**粗体**</code> - <strong>粗体</strong></li>
        <li><code>*斜体*</code> - <em>斜体</em></li>
        <li><code>[链接文本](链接地址)</code> - <a href="#">链接文本</a></li>
        <li><code>![图片描述](图片地址)</code> - 插入图片</li>
        <li><code>```代码块```</code> - 代码块</li>
        <li><code>- 列表项</code> - 无序列表</li>
        <li><code>1. 列表项</code> - 有序列表</li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { addDiscuss } from '../../services/discuss';
import type { DiscussAddParams } from '../../services/discuss';
import { useUserStore } from '../../stores/user';
import { marked } from 'marked';

const router = useRouter();
const userStore = useUserStore();
const discussFormRef = ref();
const loading = ref(false);
const previewVisible = ref(false);

// 检查用户是否已登录
if (!userStore.isAuthenticated) {
  ElMessage.warning('请先登录后再发布讨论');
  router.push('/login');
}

const discussForm = reactive<DiscussAddParams>({
  title: '',
  content: '',
  tags: [] as string[]
});

const rules = {
  title: [
    { required: true, message: '请输入讨论标题', trigger: 'blur' },
    { min: 3, max: 100, message: '标题长度在 3 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入讨论内容', trigger: 'blur' },
    { min: 10, max: 5000, message: '内容长度在 10 到 5000 个字符', trigger: 'blur' }
  ]
};

// 预设标签
const predefinedTags = [
  'OpenAI',
  '通义千问',
  '讯飞星火',
  '文心一言',
  '豆包',
  'AI绘画',
  'AI对话',
  '技术交流',
  '经验分享',
  '问题求助'
];

// 返回列表
const goBack = () => {
  router.push('/discuss');
};

// 切换预览
const togglePreview = () => {
  previewVisible.value = !previewVisible.value;
};

// 渲染Markdown
const renderMarkdown = (content: string) => {
  if (!content) return '';
  return marked(content);
};

// 提交表单
const handleSubmit = async () => {
  if (!userStore.isAuthenticated) {
    ElMessage.warning('请先登录后再发布讨论');
    router.push('/login');
    return;
  }
  
  if (!discussFormRef.value) return;
  
  await discussFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        await addDiscuss({
          ...discussForm,
          tags: discussForm.tags
        });
        ElMessage.success('发布成功');
        router.push('/discuss');
      } catch (error: any) {
        ElMessage.error(error.message || '发布失败');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  if (discussFormRef.value) {
    discussFormRef.value.resetFields();
    discussForm.tags = [];
  }
};
</script>

<style scoped>
.discuss-add-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.back-link {
  margin-bottom: 20px;
}

h2 {
  margin-bottom: 30px;
  color: var(--el-text-color-primary);
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 10px;
}

.predefined-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 5px;
}

.predefined-tags .el-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.predefined-tags .el-tag:hover:not(.tag-disabled) {
  transform: translateY(-2px);
}

.tag-disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.tags-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 5px;
}

.content-editor {
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
}

.editor-toolbar {
  padding: 8px;
  border-bottom: 1px solid var(--el-border-color);
  background: var(--el-bg-color-page);
}

.editor-container {
  padding: 20px;
}

.preview-container {
  min-height: 300px;
  padding: 20px;
  background: var(--el-bg-color-page);
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.markdown-tips {
  margin-top: 30px;
  padding: 20px;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  border: 1px solid var(--el-border-color);
}

.markdown-tips h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: var(--el-text-color-primary);
}

.markdown-tips ul {
  padding-left: 20px;
  margin: 0;
}

.markdown-tips li {
  margin-bottom: 8px;
  color: var(--el-text-color-regular);
}

.markdown-tips code {
  background: var(--el-bg-color);
  padding: 2px 5px;
  border-radius: 3px;
  color: var(--el-text-color-primary);
  font-family: monospace;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

@media (max-width: 768px) {
  .discuss-add-container {
    margin: 10px;
    padding: 15px;
  }
  
  .preview-container {
    padding: 15px;
  }
}
</style> 